package com.hdax.dm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.beans.user.User;
import com.hdax.dm.constant.ErrConstant;
import com.hdax.dm.exceptions.DmException;
import com.hdax.dm.mappers.registerMapper;
import com.hdax.dm.service.registerService;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class registerServiceImpl extends ServiceImpl<registerMapper,User> implements registerService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public CommonResponse<Integer> register(Map<String, Object> params) {
        String phone = (String) params.get("phone");
        String password = (String) params.get("password");
        String vcode = (String) params.get("vcode");

        //根据指定的key从redis中读取数据
        String key = "vcode:"+phone;
        String realCvode = redisTemplate.opsForValue().get(key);

        //如果realCvode他是空的，则说明验证码不存在
        if (realCvode == null) {
            throw new DmException(ErrConstant.ErrCodeConstant.NOT_EXISTS_CODE_VCODE,ErrConstant.ErrMsgConstant.NOT_EXISTS_MSG_VCODE);
        }
        //获取验证码不为空，但是输入的和获取的不相等，则说明验证码输入错误
        if (!realCvode.equals(vcode)){
            throw new DmException(ErrConstant.ErrCodeConstant.WRONG_CODE_VCODE,ErrConstant.ErrMsgConstant.WRONG_MSG_VCODE);
        }

        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setNickName(phone);
        user.setRealName(phone);

        int i = baseMapper.insert(user);
        return ResponseUtil.returnSuccess(i);
    }


}
